<?php
	$valid = true;
	$total = 0;
	if(isset($_GET['id'])){
		require_once('conn.php');
		$qid = $_GET['id'];
		$totalQuery = mysql_query("select sum(vote) as total from mc where qid = $qid");
		if($sum = mysql_fetch_assoc($totalQuery)){
			
			
			if((!isset($_GET['prev']) || (isset($_GET['prev']) && $sum['total'] > $_GET['prev']))){	
				
				
				if($sum['total'] > 0){	
					$total = $sum['total'];
					$answerArray = mysql_query("select choice,vote from mc where qid = $qid");
					$choiceNum = mysql_num_rows($answerArray);
					$imageHeight = 250+$choiceNum*100;
					$image = imagecreate(750,$imageHeight);
					$background = imagecolorallocate($image, 191, 191, 191);
					$black = imagecolorallocate($image, 0, 0, 0);
					$white = imagecolorallocate($image, 255, 255, 255);
					$blue = imagecolorallocate($image, 0, 0, 255);
					imageline($image,100,$imageHeight-100,650,$imageHeight-100,$black);
					imageline($image,100,100,100,$imageHeight-100,$black);
					
					imagestring($image, 5, 100-15, $imageHeight-90, '0%', $white);
					for($i = 0; $i < 5; $i++){
						imageline($image, 200+$i*100, 150, 200+$i*100, $imageHeight-100, $white);
						imagestring($image, 5, 200+$i*100-15, $imageHeight-90, 20*($i+1).'%', $white);
					}
					mysql_data_seek($answerArray, 0);
					$i = 0;
					while($answer = mysql_fetch_assoc($answerArray)){
						imagestring($image, 5, 100-30,250+100*$i-55 ,chr(65+$i), $black);
						$percentage = round($answer['vote']/$sum['total']*100,2);
						imagefilledrectangle($image, 100, 250+100*$i-20, 100+$percentage/20*100, 250+100*$i-80, $blue);
						imagestring($image, 5, 100+$percentage/20*100+20,250+100*$i-55 ,$percentage.'%', $blue);
						$i++;
					}
				}
				else{
					$image = imagecreate(200,200);
					$background = imagecolorallocate($image, 255, 255, 255);
				}
			}
			else{
				echo json_encode(array('image'=>''));
			}
		}
		mysql_close($connect);
	}
	else{
		$valid = false;
	}
	if(!$valid){	
		$image = imagecreate(200,200);
		$background = imagecolorallocate($image, 191, 191, 191);
		$black = imagecolorallocate($image, 0, 0, 0);
		imagestring($image, 5, 35, 100, 'Invalid access!', $black);
	}
	
	if(isset($_GET['prev']) && ($total != 0)){
		ob_start();
		imagepng($image);
		$image_data=ob_get_contents();
		ob_end_clean();
		$image_data_base64=base64_encode($image_data);
		echo json_encode(array('image'=>$image_data_base64,'total'=>$total));
	}
	else if(!isset($_GET['prev'])){
		header("Content-type:image/png");
		imagepng($image);
		imagedestroy($image);
		
	}

        
?>
